package cn.wolfcode.mq;

import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import com.google.j2objc.annotations.AutoreleasePool;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.annotation.Order;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
import sun.plugin2.message.Message;

/**
 * @author hkj
 * @email 1349091387@qq.com
 * @date 2022/1/2
 * 源码允许修改，并且本人十分乐意有 大佬 来对代码进行 随 意 调 教
 **/
@Slf4j
@Component
@RocketMQMessageListener(
        consumerGroup = "MQOrderPeddingListener",
        topic = MQConstant.ORDER_PEDDING_TOPIC
)
public class MQOrderPeddingListener implements RocketMQListener<OrderMessage> {

    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(OrderMessage orderMessage) {
        log.info("调用了创建订单的消费者");
        Long seckillId = orderMessage.getSeckillId();
        Integer time = orderMessage.getTime();
        String token = orderMessage.getToken();
        Long phone = orderMessage.getUserPhone();

        OrderMQResult orderMQResult = new OrderMQResult();
        orderMQResult.setToken(token);
        orderMQResult.setSeckillId(seckillId);
        orderMQResult.setTime(time);

        String tag = "";
        try {
            ////int i = 1 / 0;
            //执行秒杀逻辑
            String orderNo = orderInfoService.doSeckill(time, seckillId, phone);
            orderMQResult.setOrderNo(orderNo);
            //封装orderMQResult对象，同时设置一下标签，并进行发送
            tag = MQConstant.ORDER_RESULT_SUCCESS_TAG;

            //发送一个延时消息
            MessageBuilder<OrderMQResult> builder = MessageBuilder.withPayload(orderMQResult);
            rocketMQTemplate.syncSend(MQConstant.ORDER_PAY_TIMEOUT_TOPIC, builder.build(), 5000, 5);
        } catch (Exception e) {
            e.printStackTrace();
            orderMQResult.setCode(SeckillCodeMsg.SECKILL_ERROR.getCode());
            orderMQResult.setMsg(SeckillCodeMsg.SECKILL_ERROR.getMsg());
            tag = MQConstant.ORDER_RESULT_FAIL_TAG;
        }
        rocketMQTemplate.sendOneWay(MQConstant.ORDER_RESULT_TOPIC + ":" + tag,orderMQResult);
    }
}
